import React, { FC, useRef, useEffect, useMemo, useState, useCallback } from 'react';
import './style.less';
import Cookies from 'js-cookie'

// import {message1} from '../../network/config';
import {
  Form, Input, Button, Select, InputNumber, Upload, Cascader, message
} from 'antd';
// import moment from 'moment';
import { provinceData, provinceData1 } from './conf';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { add, getDetail, update } from '../../network/protocol'
import { baseUrl } from '../../network/myFetch'
const Option = Select.Option;


interface param {
  artistName: string;  //性别
  artworkName: string;//名称
  createYear: number;//年代
  artworkType: string;//类型
  material: string;//材质
  form: string;//形式
  size: string;//尺寸
  typeface: string;//字体
  publishList: Array<string>;// 出版记录
  exhibitionList: Array<string>;// 展览记录
  storePlace: string; //存放地点
  source: string;//作品来源
  price: number; //
  imageUrl: string;
  sex: string;
}

interface param1 extends param {
  width: number;
  height: number;
  number: number;
}


const layout = {
  labelCol: { span: 2 },
  wrapperCol: { span: 8 },
};

const initData: param = {
  artistName: '胡问遂',
  artworkName: '',//名称
  createYear: 0,//年代
  artworkType: '',//类型
  material: '',//材质
  form: '',//形式
  size: '',//尺寸
  typeface: '',//字体
  publishList: [],// 出版记录
  exhibitionList: [],// 展览记录
  storePlace: '', //存放地点
  source: '',//作品来源
  price: 100, //
  imageUrl: '',
  sex: '男',
}

const initData1 = {
  artistName: '胡问遂',
  artworkName: '作品名称',//名称
  createYear: 2000,//年代
  artworkType: '国画-纸本水墨',//类型  ['国画', '纸本水墨']
  material: '水彩画-纸本水彩',//材质  ['水彩画', '纸本水彩']
  form: '书法',//形式
  size: '100-100-4',//尺寸
  typeface: '草书',//字体
  publishList: ['人民出版社', '新华出版社'],// 出版记录
  exhibitionList: ['图书馆', '报社'],// 展览记录
  storePlace: '博物馆', //存放地点
  source: '捐赠',//作品来源
  price: 100, //
  imageUrl: 'http://122.51.187.170:8456/artwork_sys/uploadfile/1606147495844.jpg',
  //=====
  width: 100,
  height: 100,
  number: 4,
  sex: '男',
  content: '这是内容'
}

// function getBase64(img:any, callback:any) {
//   const reader = new FileReader();
//   reader.addEventListener('load', () => callback(reader.result));
//   reader.readAsDataURL(img);
// }

const Manage: FC = (props: any) => {

  let formR = useRef(null) as any;
  const [loading, setLoading] = useState(false);
  const [url, setUrl] = useState('');

  // const [initv, setI] = useState((()=>{
  //   let d: any = { ...initData1 };
  //   d.publishList = d.publishList.join(',');
  //   d.exhibitionList = d.exhibitionList.join(',');
  //   d.artworkType = d.artworkType.split('-');
  //   d.material = d.material.split('-');
  //   return d 
  // })())

  const id1 = useMemo(() => {
    return props.computedMatch.params.id
  }, [props])

  const getDetail1 = useCallback(async () => {
    if(!id1) return
    try {
      let res = await getDetail(id1)
      if (res.errorCode === 0) {
        let d = res.source;
        console.log(res.source)
        d.artistName = d.artistName || '胡问遂';
        d.publishList = d.publishList.join(',');
        d.exhibitionList = d.exhibitionList.join(',');
        d.artworkType = d.artworkType.split('-');
        d.material = d.material.split('-');
        let size = d.size.split('*');
        d.width = size[0];
        d.height = size[1];
        d.number = size[2];
        setUrl(d.imageUrl);
        formR.current.setFieldsValue(d)

      }
    } catch (error) {

    }
  }, [id1])

  const initv = useMemo(() => {
    let d: any = { ...initData1 };

    d.publishList = d.publishList.join(',');
    d.exhibitionList = d.exhibitionList.join(',');
    d.artworkType = d.artworkType.split('-');
    d.material = d.material.split('-');
    return d
  }, [])


  const onFinish = useCallback(async (e: any): Promise<void> => {


    // return
    let d = e;
    d.artworkType = d.artworkType.join('-');
    d.material = d.material.join('-');
    d.publishList = d.publishList.split(',');
    d.exhibitionList = d.exhibitionList.split(',');
    d.size = `${d.width}*${d.height}*${d.number}`;
    delete d.width;
    delete d.height;
    delete d.number;
    d.imageUrl = url;
    console.log(d);

    let f = add;
    if (id1) {
      f = update;
      d.id = id1;
    }
    try {
      let data = await f(d);
      if (data.errorCode !== 0) {
        message.error(data.message)
      } else {
        message.success('成功！')
    formR.current.setFieldsValue(initv)


      }
    } catch (error) {
      console.log(error)
    }

  }, [id1,initv,url])

  // async function onFinish (e: any) {
  //   let d = initv;
  //   d.artworkType = d.artworkType.join('-');
  //   d.material = d.material.join('-');
  //   d.publishList = d.publishList.split(',');
  //   d.exhibitionList = d.exhibitionList.split(',');
  //       delete d.width;
  //   delete d.height;
  //   delete d.number;
  //   let data = await add(d)
  //   console.log(data)

  // }


  const onFinishFailed = (): void => { }

  const normFile = (e: any) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  const handleChange = (info: any) => {

    if (info.file.status === 'uploading') {
      setLoading(true)
    }
    console.log(info)
    if (info.file.status === 'done') {
      if (info.file.response.errorCode !== 0) {
        message.error(info.file.response.message)
      } else {
        message.success('图片上传成功')
        setUrl(info.file.response.source)

      }
      // Get this url from response in real world.
      // getBase64(info.file.originFileObj, (imageUrl:any) => {
      //   setLoading(true)
      //   setUrl(imageUrl)    
      // }
      // );
    }
  }

  const beforeUpload = (file: any) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;

  }

  useEffect(() => {
    getDetail1();
  }, [getDetail1])


  return (
    <>

      <Form
        name="basic"
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        initialValues={{ ...initv }}
        ref={formR}
      >

        <Form.Item
          label="作家"
          name="artistName"
          {...layout}
          labelAlign='left'
          // rules={[{ required: true }]}
        >
          <Input disabled />
        </Form.Item>

        <Form.Item
          label="性别"
          name="sex"
          {...layout}
          labelAlign='left'
          // rules={[{ required: true }]}
        >
          <Select
            allowClear
          >
            <Option value="男">男</Option>
            <Option value="女">女</Option>
          </Select>
        </Form.Item>

        <Form.Item
          label="作品名称"
          name="artworkName"
          {...layout}
          labelAlign='left'
          // rules={[{ required: true }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="创作年代"
          name="createYear"
          {...layout}
          labelAlign='left'
        >
          <InputNumber />
        </Form.Item>

        <Form.Item
          name="artworkType"
          label="作品类型"
          // required
          {...layout}
          labelAlign='left'

        >
          <Cascader options={provinceData} />
        </Form.Item>


        <Form.Item
          name="material"
          label="作品材质"
          // required
          {...layout}
          labelAlign='left'

        >
          <Cascader options={provinceData1} />
        </Form.Item>

        <Form.Item
          label="作品形式"
          name="form"
          {...layout}
          labelAlign='left'
          // rules={[{ required: true }]}
        >
          <Select
            allowClear
          >
            <Option value="书法">书法</Option>
            <Option value="条幅">条幅</Option>
            <Option value="横幅">横幅</Option>
            <Option value="对联">对联</Option>
            <Option value="四条屏">四条屏</Option>
            <Option value="扇面">扇面</Option>
            <Option value="册页">册页</Option>
            <Option value="手卷">手卷</Option>
            <Option value="其它">其它</Option>
          </Select>
        </Form.Item>

        <Form.Item
          label="尺寸"
          {...layout}
          wrapperCol={{ span: 18 }}
          labelAlign='left'
          // rules={[{ required: true, }]}
        >
          <Form.Item
            name="height"
            // rules={[{ required: true }]}
            style={{ display: 'inline-block', }}

          >
            <InputNumber placeholder="长,单位cm" style={{ width: 200 }} />
          </Form.Item>
          <Form.Item
            name="width"
            // rules={[{ required: true }]}
            style={{ display: 'inline-block', }}
          >
            <InputNumber placeholder="宽,单位cm" style={{ width: 200 }} />
          </Form.Item>
          <Form.Item
            name="number"
            // rules={[{ required: true, }]}
            style={{ width: 200, display: 'inline-block' }}

          >
            <Input placeholder="数量" />
          </Form.Item>
        </Form.Item>

        <Form.Item
          label="书体"
          name="typeface"
          {...layout}
          labelAlign='left'
          // rules={[{ required: true, }]}
        >
          <Select
            allowClear
          >
            {/* <Option value="隶书">隶书</Option> */}
            <Option value="行书">行书</Option>
            <Option value="正楷">正楷</Option>
            <Option value="草书">草书</Option>
            <Option value="篆书">篆书</Option>

          </Select>
        </Form.Item>

        <Form.Item
          label="出版记录"
          name="publishList"
          {...layout}
          labelAlign='left'
          // rules={[{ required: true, }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="展览记录"
          name="exhibitionList"
          {...layout}
          labelAlign='left'
          // rules={[{ required: true, }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="存放地点"
          name="storePlace"
          {...layout}
          labelAlign='left'
          // rules={[{ required: true, }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="作品来源"
          name="source"
          {...layout}
          labelAlign='left'
          // rules={[{ required: true, }]}
        >
          <Select
            allowClear
          >
            <Option value="纂书">捐赠</Option>
            <Option value="隶书">购买</Option>
            <Option value="草书">置换</Option>
            <Option value="行书">借展</Option>
          </Select>
        </Form.Item>


        <Form.Item
          label="价值"
          name="price"
          {...layout}
          labelAlign='left'
          // rules={[{ required: true, }]}
        >
          <InputNumber />
        </Form.Item>

        <Form.Item
          // name="imageUrl"
          label="图片"
          labelAlign='left'
          valuePropName="imageUrl"
          {...layout}
          getValueFromEvent={normFile}
          // required
        >
          <Upload
            name="file"
            listType="picture-card"
            className="avatar-uploader"
            showUploadList={false}
            action={`${baseUrl}/artwork_sys/admin/upload/img`}
            // action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
            beforeUpload={beforeUpload}
            onChange={handleChange}
            accept="*"
            headers={{ token: Cookies.get('token') }}
          >
            {url ? < img src={url} alt="avatar" style={{ width: '100%' }} />
              :
              <div>
                {loading ? <LoadingOutlined /> : <PlusOutlined />}
                <div style={{ marginTop: 8 }}>Upload</div>
              </div>}
          </Upload>
        </Form.Item>

        <Form.Item
          label="内容"
          name="content"
          {...layout}
          labelAlign='left'
          // rules={[{ required: true, }]}
        >
          <Input.TextArea />
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit">
            Submit
          </Button>
        </Form.Item>
      </Form>
    </>


  );

};




export default Manage;